package com.nnnu.wsnackshop.controller.admin;

import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.DeliveryDTO;
import com.nnnu.wsnackshop.pojo.dto.OrderPageQueryDTO;
import com.nnnu.wsnackshop.pojo.vo.OrderVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IOrdersService;
import com.nnnu.wsnackshop.service.IRidersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 管理员端-订单 前端控制器
 * </p>
 */
@RestController("adminOrdersController")
@RequestMapping("/api/admin/orders")
@Tag(name = "管理员端-订单接口")
@Slf4j
@RequiresRoles(value = { "admin", "superAdmin" }, logical = Logical.OR)
@RequiredArgsConstructor
public class OrdersController extends BaseController {

    private final IOrdersService ordersService;
    private final IRidersService ridersService;

    /**
     * 获取订单列表
     */
    @GetMapping
    @Operation(summary = "获取订单列表", description = "管理员获取订单分页列表")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<PageResult<OrderVO>> getOrders(OrderPageQueryDTO queryDTO) {
        log.info("[管理员] 获取订单列表, 参数: {}", queryDTO);
        PageResult<OrderVO> pageResult = ordersService.getOrdersForAdmin(queryDTO);
        return Result.success(pageResult);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取订单详情", description = "管理员获取订单详情")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    public Result<OrderVO> getOrderDetail(@PathVariable("id") Long orderId) {
        log.info("[管理员] 获取订单详情, orderId: {}", orderId);
        // 管理员查看订单详情不需要传递用户ID
        OrderVO orderVO = ordersService.getOrderDetail(null, orderId);
        return Result.success(orderVO);
    }

    /**
     * 确认自提订单准备完成
     * 用于商家确认自提订单已准备好，等待用户取货
     */
    @PostMapping("/{id}/ready-for-pickup")
    @Operation(summary = "确认自提订单准备完成", description = "管理员确认自提订单已准备好，等待用户取货")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("order:manage")
    public Result<Boolean> confirmReadyForPickup(@PathVariable Long id) {
        log.info("确认自提订单准备完成: orderId={}", id);
        boolean success = ordersService.confirmReadyForPickup(id);
        return Result.success(success);
    }

    /**
     * 确认同城配送订单准备完成
     * 用于商家确认同城配送订单已准备好，可以进行分配骑手
     */
    @PostMapping("/{id}/ready-for-delivery")
    @Operation(summary = "确认同城配送订单准备完成", description = "管理员确认同城配送订单已准备好，可以进行分配骑手")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("order:manage")
    public Result<Boolean> confirmLocalOrderReady(@PathVariable Long id) {
        log.info("确认同城配送订单准备完成: orderId={}", id);
        boolean success = ordersService.confirmLocalOrderReady(id);
        return Result.success(success);
    }

    /**
     * 自动分配骑手
     */
    @PostMapping("/{id}/assign-rider")
    @Operation(summary = "自动分配骑手", description = "管理员手动触发自动分配骑手")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("order:manage")
    public Result<Integer> autoAssignRider(@PathVariable Long id) {
        log.info("手动触发自动分配骑手: orderId={}", id);
        Integer riderId = ordersService.autoAssignRider(id);

        if (riderId != null) {
            log.info("自动分配骑手成功: orderId={}, riderId={}", id, riderId);
            return Result.success(riderId);
        } else {
            log.warn("没有可用骑手，分配失败: orderId={}", id);
            return Result.error(500, "没有可用骑手，请稍后再试");
        }
    }

    /**
     * 手动分配骑手
     */
    @PostMapping("/{id}/manual-assign-rider")
    @Operation(summary = "手动分配骑手", description = "管理员手动分配指定骑手")
    @RequiresRoles(value = { "superAdmin", "admin" }, logical = Logical.OR)
    @RequiresPermissions("order:manage")
    public Result<Boolean> manualAssignRider(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> requestBody) {

        Integer riderId = requestBody.get("riderId");
        if (riderId == null) {
            return Result.error(400, "骑手ID不能为空");
        }

        log.info("手动分配骑手: orderId={}, riderId={}", id, riderId);
        boolean success = ridersService.manualAssignRider(id, riderId);

        if (success) {
            log.info("手动分配骑手成功: orderId={}, riderId={}", id, riderId);
            return Result.success(true, "骑手分配成功");
        } else {
            log.warn("手动分配骑手失败: orderId={}, riderId={}", id, riderId);
            return Result.error(500, "骑手分配失败，请稍后再试");
        }
    }
}